//
//  SEGBottomPopController.m
//  Uhomebk
//
//  Created by mac on 2017/8/9.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "SEGBottomPopController.h"
#import "SEGBottomPopCell.h"
#import "SEGOrderInputChildModel.h"
#import "SEGBasicBussinessCommonDefine.h"

static  NSString *const kCellId = @"SEGBottomPopCell";

@interface SEGBottomPopController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *typeDataArray;/**类型配置数据源 */
@property(nonatomic,strong)NSMutableArray *statusDataArray;/**状态配置数据源 */
@property(nonatomic,strong)NSMutableArray *communityDataArray;/**小区配置数据源 */
@property(nonatomic,strong)NSMutableArray *inputTypeDataArray;/**录入服务信息数据源 */
@property(nonatomic,strong)NSMutableArray *bespealDataArray;/**预约时间段数据源 */
@property(nonatomic,strong)NSMutableArray *dataArray;/**需要展示的数据源 */
@property(nonatomic,assign)SEGBottomPopControllerType popVCType;/**弹出组件菜单类型 */
@property(nonatomic,copy)SEGBottomPopVCCellClickCallBack cellClick;/**弹出组件菜单类型 */

@end


@implementation SEGBottomPopController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    [self.view addSubview:bgView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeView:)];
    [bgView addGestureRecognizer:tap];
    [self.view addSubview:self.tableView];

    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(0);
    }];
}

/**
 弹出底部框
 cellClick 点击cell 回调
 */
-(void)segBottomPopControllerShowWith:(SEGBottomPopControllerType)popVCType cellClick:(SEGBottomPopVCCellClickCallBack)cellClick
{
    _popVCType = popVCType;
    _cellClick = cellClick;
    
    switch (popVCType) {
            //1.工单类型菜单
        case SEGBottomPopControllerType_TYPE_MENU_LIST:
            
            _dataArray = _typeDataArray;
            break;
        
            //2.工单状态菜单
        case SEGBottomPopControllerType_STATUS_MENU_LIST:
            
           _dataArray = _statusDataArray;
            break;
        
            //3.小区菜单
        case SEGBottomPopControllerType_COMMUNITY_MENU_LIST:
           
            _dataArray = _communityDataArray;
            break;
            //4.服务类型
        case SEGBottomPopControllerType_ORDER_INPUT_SERVICE_LIST:
            
            _dataArray = _inputTypeDataArray;
            break;
            //5.预约时间段
        case SEGBottomPopControllerType_BESPEL_TIME_LIST:
            
            _dataArray = _bespealDataArray;
            break;
        default:
            break;
    }
    //3.更新高度
    CGFloat boxHeight = 250;
    boxHeight = _dataArray.count > 5?250:50*_dataArray.count;
    [self.tableView reloadData];
    [self refreshTableViewConstraintsWithHeight:boxHeight];
    
    //弹出视图
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    
    if (@available(iOS 8.0, *)) {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    } else {
        self.modalPresentationStyle = UIModalPresentationCurrentContext;
    }
    //25784 【深到家v1.1.0】IOS 工单无法选择服务分类
    UIViewController *currentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
    [currentVC presentViewController:self animated:YES completion:nil];
}


/**
 隐藏底部框
 */
-(void)segBottomPopControllerHide
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



/**
 配置数据源
 */
-(void)configDataArrayWithDataArray:(NSArray *)dataArray popVCType:(SEGBottomPopControllerType)popVCType
{
    if (dataArray == nil) {
        return;
    }
    switch (popVCType) {
            //1.工单类型菜单
        case SEGBottomPopControllerType_TYPE_MENU_LIST:
            [self configTypeMenuData:dataArray];
            break;
            //2.工单状态菜单
        case SEGBottomPopControllerType_STATUS_MENU_LIST:
            [self configStatusMenuData:dataArray];
            break;
            //3.小区菜单
        case SEGBottomPopControllerType_COMMUNITY_MENU_LIST:
            [self configCommunityMenuData:dataArray];
            break;
            //4.工单录入服务类型列表
        case SEGBottomPopControllerType_ORDER_INPUT_SERVICE_LIST:
            [self configOrderInputServiceTypeWith:dataArray];
            break;
            //5.预约时间段列表
        case SEGBottomPopControllerType_BESPEL_TIME_LIST:
            [self configBespelTimeListWith:dataArray];
            break;
        default:
            break;
    }
}


/**
 配置预约时间段列表数据源
 */
-(void)configBespelTimeListWith:(NSArray *)dataArray
{
    [self.bespealDataArray removeAllObjects];
    __block BOOL isHaveDefault = NO;
    [dataArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSMutableDictionary *timeDict = [[NSMutableDictionary alloc] init];
        NSString *bespeakStart = CHECKVALUE(dict[@"bespeakStart"]);
        NSString *bespeakEnd = CHECKVALUE(dict[@"bespeakEnd"]);
        //显示的时间
        [timeDict setValue:dict[@"name"] forKey:@"bespealTimes"];//展示的值
        [timeDict setValue:dict[@"value"] forKey:@"value"];//提交的值
        [timeDict setObject:bespeakStart forKey:@"bespeakStart"];//做检验的值
        [timeDict setObject:bespeakEnd forKey:@"bespeakEnd"];//做检验的值
        [timeDict setValue:@"NO" forKey:@"isSelected"];
        //设置默认勾选
        if (isHaveDefault == NO && [self checkIsBespealTimesWith:@{@"bespeakEnd":bespeakEnd}]) {
            [timeDict setValue:@"YES" forKey:@"isSelected"];
            isHaveDefault = YES;
        }
        [_bespealDataArray addObject:timeDict];
        
    }];
    
    //3.更新高度
    CGFloat boxHeight = 250;
    boxHeight = _bespealDataArray.count > 5?250:50*_bespealDataArray.count;
    [self refreshTableViewConstraintsWithHeight:boxHeight];
}

#pragma mark - ===============<校验时间是否超出范围>===============
/**
 校验时间是否超出范围

 @param dict 要校验的字典
 @return YES-校验通过 NO-校验不通过
 */
-(BOOL)checkIsBespealTimesWith:(NSDictionary *)dict{
    //结束时间
    NSString *endTime = dict[@"bespeakEnd"];
    //预约日期
    NSString *dateStr = self.tempValue;
    //如果结束时间比当前时间早 则不通过
    NSString *selectTime = [SEGUtils getTimeStrWithDate:dateStr milliSecond:endTime formatterStr:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *selectDate = [SEGUtils dateFromString:selectTime withFormatString:@"yyyy-MM-dd HH:mm:ss"];
    if ([selectDate isInPast]) {
        return NO;
    }
    return YES;
}

-(void)refreshUI
{
    [self.tableView reloadData];
}

- (void)refreshTableViewConstraintsWithHeight:(CGFloat)height {
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

/**
 配置工单录入服务类型列表
 */
-(void)configOrderInputServiceTypeWith:(NSArray *)dataArray
{
    [self.inputTypeDataArray removeAllObjects];
    [dataArray enumerateObjectsUsingBlock:^(SEGOrderInputChildModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSMutableDictionary *inputDict = [[NSMutableDictionary alloc] init];
        [inputDict setValue:model.busiName forKey:@"busiName"];
        [inputDict setValue:model.busiCode forKey:@"busiCode"];
        [inputDict setValue:model.busiTypeId forKey:@"busiTypeId"];
        [inputDict setValue:idx == 0 ? @"YES" : @"NO"  forKey:@"isSelected"]; // [需求 11028]默认选择第一个
        [_inputTypeDataArray addObject:inputDict];
        
    }];
    
    //3.更新高度
    CGFloat boxHeight = 250;
    boxHeight = _inputTypeDataArray.count > 5?250:50*_inputTypeDataArray.count;
    [self refreshTableViewConstraintsWithHeight:boxHeight];
}

/**
 配置类型
 */
-(void)configTypeMenuData:(NSArray *)dataArray
{
    [self.typeDataArray removeAllObjects];
    
    //1.先配置全部项
    NSMutableDictionary *allDict = [[NSMutableDictionary alloc] init];
    [allDict setValue:@"全部" forKey:@"templateName"];
    [allDict setValue:@"all" forKey:@"templateId"];
    [allDict setValue:@"" forKey:@"subTemplateInstIds"];
    [allDict setValue:@"YES" forKey:@"isSelected"];
    [_typeDataArray addObject:allDict];
    
    //2.配置其他条件项
    for (NSDictionary *dict in dataArray)
    {
        NSMutableDictionary *typeDict = [[NSMutableDictionary alloc] init];
        //去重操作
       __block BOOL isHaveType = NO;
        [_typeDataArray enumerateObjectsUsingBlock:^(NSDictionary *typeDict_temp, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([typeDict_temp[@"templateId"] isEqualToString:dict[@"templateId"]] ) {
                isHaveType = YES;
            }
        }];
        
        if (isHaveType == NO) {
             [typeDict setValue:dict[@"templateName"] forKey:@"templateName"];
            [typeDict setValue:[SEGUtils ValueToString:dict[@"templateId"]] forKey:@"templateId"];
            [typeDict setValue:@"NO" forKey:@"isSelected"];
            [_typeDataArray addObject:typeDict];
        }
    }
    
    //3.更新高度
    CGFloat boxHeight = 250;
    boxHeight = _typeDataArray.count > 5?250:50*_typeDataArray.count;
    [self refreshTableViewConstraintsWithHeight:boxHeight];
}

/**
 配置状态
 */
-(void)configStatusMenuData:(NSArray *)dataArray
{
    [self.statusDataArray removeAllObjects];
   
    //1.先配置全部项
    NSMutableDictionary *allDcit = [[NSMutableDictionary alloc] init];
    [allDcit setValue:@"全部" forKey:@"statusName"];
    [allDcit setValue:@"all" forKey:@"status"];
    [allDcit setValue:@"YES" forKey:@"isSelected"];
    [self.statusDataArray addObject:allDcit];
    
    //2.配置其他条件项
    for (NSDictionary *dict in dataArray)
    {
        NSMutableDictionary *statusDict = [[NSMutableDictionary alloc] init];
        [statusDict setValue:dict[@"resultName"] forKey:@"statusName"];
        [statusDict setValue:dict[@"resultCode"] forKey:@"status"];
        [statusDict setValue:@"No" forKey:@"isSelected"];
        [_statusDataArray addObject:statusDict];
    }
    
    //3.更新高度
    CGFloat boxHeight = 250;
    boxHeight = _statusDataArray.count > 5?250:50*_statusDataArray.count;
    [self refreshTableViewConstraintsWithHeight:boxHeight];
}


/**
 配置小区
 */
-(void)configCommunityMenuData:(NSArray *)dataArray
{
    [self.communityDataArray removeAllObjects];
    
    
    for (NSDictionary *dict in dataArray)
    {
        NSMutableDictionary *communityDict = [[NSMutableDictionary alloc] init];
        [communityDict setValue:dict[@"name"] forKey:@"name"];
        [communityDict setValue:[SEGUtils ValueToString:dict[@"communityId"]] forKey:@"communityId"];
        [communityDict setValue:@"NO" forKey:@"isSelected"];
        if ([[SEGUtils ValueToString:dict[@"communityId"]] isEqualToString:kAccountCommunityID]) {
           [communityDict setValue:@"YES" forKey:@"isSelected"];
        }
       
        
        [_communityDataArray addObject:communityDict];
    }
}


#pragma mark - ================<tableView代理>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SEGBottomPopCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId forIndexPath:indexPath];
    
    NSDictionary *dict = _dataArray[indexPath.row];
    
    [cell paddingDataWith:dict popVCType:_popVCType];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dict = _dataArray[indexPath.row];
    
   //1.记录一下选择的
    switch (_popVCType) {
        //1.工单类型菜单
        case SEGBottomPopControllerType_TYPE_MENU_LIST:{
            [_typeDataArray enumerateObjectsUsingBlock:^(NSMutableDictionary *typeDict, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [typeDict setObject:@"NO" forKey:@"isSelected"];
                if ([[SEGUtils ValueToString:typeDict[@"templateId"]] isEqualToString:dict[@"templateId"]] ) {
                    [typeDict setObject:@"YES" forKey:@"isSelected"];
                }
                
            }];
            
            break;
        }
            
        //2.工单状态菜单
        case SEGBottomPopControllerType_STATUS_MENU_LIST:{
            [_statusDataArray enumerateObjectsUsingBlock:^(NSMutableDictionary *statusDict, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [statusDict setObject:@"NO" forKey:@"isSelected"];
                if ([[SEGUtils ValueToString:statusDict[@"status"]] isEqualToString:dict[@"status"]] ) {
                    [statusDict setObject:@"YES" forKey:@"isSelected"];
                }
            }];
            break;
        }
            
        //3.小区菜单
        case SEGBottomPopControllerType_COMMUNITY_MENU_LIST:{
            [_communityDataArray enumerateObjectsUsingBlock:^(NSMutableDictionary *communityDict, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [communityDict setObject:@"NO" forKey:@"isSelected"];
                if ([[SEGUtils ValueToString:communityDict[@"communityId"]] isEqualToString:[SEGUtils ValueToString:dict[@"communityId"]]] ) {
                    [communityDict setObject:@"YES" forKey:@"isSelected"];
                }
            }];
            break;
        }
        case SEGBottomPopControllerType_ORDER_INPUT_SERVICE_LIST:{
            [_inputTypeDataArray enumerateObjectsUsingBlock:^(NSMutableDictionary *inputDict, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [inputDict setObject:@"NO" forKey:@"isSelected"];
                if ([inputDict[@"busiCode"] isEqualToString:dict[@"busiCode"]] ) {
                    [inputDict setObject:@"YES" forKey:@"isSelected"];
                }
            }];
            
            break;
        }
        case SEGBottomPopControllerType_BESPEL_TIME_LIST:{
            // 先判断选择的时间是否小于当前时间 若小于则不予选择
            if (![self checkIsBespealTimesWith:@{@"bespeakEnd":dict[@"bespeakEnd"]}]) {
                [SEGAlertView showTmepMessageWithMessage:kTimeErrorToastMessage];
                return;
            }
            
            [_bespealDataArray enumerateObjectsUsingBlock:^(NSMutableDictionary *timeDict, NSUInteger idx, BOOL * _Nonnull stop) {
                [timeDict setObject:@"NO" forKey:@"isSelected"];
                if ([timeDict[@"bespealTimes"] isEqualToString:dict[@"bespealTimes"]] ) {
                    [timeDict setObject:@"YES" forKey:@"isSelected"];
                }
            }];
            
            break;
        }

        default:
            break;
    }
    
    if (_cellClick) {
        _cellClick(dict);
    }
    [self segBottomPopControllerHide];
    
    [tableView reloadData];
    
}


/**
 关闭事件
  */
-(void)closeView:(UIGestureRecognizer *)recognizer
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - ================<懒加载>===============
-(NSMutableArray *)typeDataArray{
    if (!_typeDataArray) {
        _typeDataArray = [[NSMutableArray alloc] init];
    }
    return _typeDataArray;
}

-(NSMutableArray *)statusDataArray{
    if (!_statusDataArray) {
        _statusDataArray = [[NSMutableArray alloc] init];
    }
    return _statusDataArray;
}

-(NSMutableArray *)communityDataArray{
    if (!_communityDataArray) {
        _communityDataArray = [[NSMutableArray alloc] init];
    }
    return _communityDataArray;
}


-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(NSMutableArray *)inputTypeDataArray{
    if (!_inputTypeDataArray) {
        _inputTypeDataArray = [[NSMutableArray alloc] init];
    }
    return _inputTypeDataArray;
}
-(NSMutableArray *)bespealDataArray{
    if (!_bespealDataArray) {
        _bespealDataArray = [[NSMutableArray alloc] init];
    }
    return _bespealDataArray;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
    }
    return _tableView;
}

@end
